package cn.qianxun.meta.upload.controller;

import cn.qianxun.meta.common.core.utils.StringUtils;
import cn.qianxun.meta.common.core.domain.Result;
import cn.qianxun.meta.common.core.exception.ServiceException;
import cn.qianxun.meta.upload.service.IUploadService;
import cn.qianxun.meta.upload.vo.FlowableUploadVO;
import cn.qianxun.meta.upload.vo.UploadFileVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * @Author fuzhilin
 * @Date 2023/9/6 11:38
 * @Description
 */
@Tag(name = "上传管理")
@RestController
@RequestMapping("/web/v1/upload")
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class UploadController {
    private final IUploadService uploadService;

    /**
     * 向传递的bucketName中上传文件
     */
    @PostMapping(value = "/uploadByBucketName")
    public Result<UploadFileVO> uploadByBucketName(@RequestParam String bucketName, @RequestPart(value = "file") MultipartFile file) {
        return Result.success("操作成功", uploadService.uploadByBucketName(bucketName, file));
    }

    /**
     * 向传递的bucketName中上传文件(token在param)
     */
    @PostMapping(value = "/authUploadByBucketName")
    public FlowableUploadVO authUploadByBucketName(String bucketName, String Authorization, @RequestPart(value = "file") MultipartFile file) {
        return uploadService.authUploadByBucketName(bucketName, file);
    }

    /**
     * 根据文件id下载资源
     *
     * @param fileId   文件id
     * @param response response
     */
    @GetMapping("/downloadByFileId")
    public void downloadByFileId(@RequestParam String fileId, HttpServletResponse response) {
        uploadService.downloadByFileId(fileId, response);
    }

    /**
     * 根据文件id获取预览地址
     *
     * @param fileId fileId
     * @return 预览地址
     */
    @GetMapping("/getPreviewByFileId")
    public Result<String> getPreviewByFileId(@RequestParam String fileId) {
        if (StringUtils.isEmpty(fileId)) {
            throw new ServiceException("文件id不能为空");
        }
        return Result.success("获取成功", uploadService.getPreviewByFileId(fileId));
    }
}
